<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="js,时间差," />





  <link rel="alternate" href="/atom.xml" title="OBKoro1's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="写在前面：如题，就像题目说的需要计算出时间差，虽然不太难，但这个需求经常会在项目中遇到的，我在这边做一下整理，希望能够尽量全的整理出来。有需要的朋友可以做一下参考，喜欢的可以点波赞，或者关注一下，希望可以帮到大家。 计算时间差原理：getTime()方法方法定义： getTime() 方法可返回距 1970 年 1 月 1 日之间的毫秒数。 通常我们计算时间差都是通过获取两个时间数据，然后分别使用">
<meta name="keywords" content="js,时间差">
<meta property="og:type" content="article">
<meta property="og:title" content="js 计算两个时间的时间差">
<meta property="og:url" content="http://yoursite.com/2017/10/15/js-计算两个时间的时间差/index.html">
<meta property="og:site_name" content="OBKoro1&#39;s Blog">
<meta property="og:description" content="写在前面：如题，就像题目说的需要计算出时间差，虽然不太难，但这个需求经常会在项目中遇到的，我在这边做一下整理，希望能够尽量全的整理出来。有需要的朋友可以做一下参考，喜欢的可以点波赞，或者关注一下，希望可以帮到大家。 计算时间差原理：getTime()方法方法定义： getTime() 方法可返回距 1970 年 1 月 1 日之间的毫秒数。 通常我们计算时间差都是通过获取两个时间数据，然后分别使用">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/3ffd4a7df082edd1f1ed6e413cfc35eb?raw=true">
<meta property="og:updated_time" content="2019-06-15T06:19:47.629Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="js 计算两个时间的时间差">
<meta name="twitter:description" content="写在前面：如题，就像题目说的需要计算出时间差，虽然不太难，但这个需求经常会在项目中遇到的，我在这边做一下整理，希望能够尽量全的整理出来。有需要的朋友可以做一下参考，喜欢的可以点波赞，或者关注一下，希望可以帮到大家。 计算时间差原理：getTime()方法方法定义： getTime() 方法可返回距 1970 年 1 月 1 日之间的毫秒数。 通常我们计算时间差都是通过获取两个时间数据，然后分别使用">
<meta name="twitter:image" content="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/3ffd4a7df082edd1f1ed6e413cfc35eb?raw=true">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/10/15/js-计算两个时间的时间差/"/>





  <title>js 计算两个时间的时间差 | OBKoro1's Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?64d57d0b926bbd27431daa89d2e0a76b";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">OBKoro1's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-前端算法">
          <a href="/arithmetic/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            前端算法
          </a>
        </li>
      
        
        <li class="menu-item menu-item-博客最新更新">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            博客最新更新
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/10/15/js-计算两个时间的时间差/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="OBKoro1">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/hand1.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="OBKoro1's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">js 计算两个时间的时间差</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-10-15T20:07:31+08:00">
                2017-10-15
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/js/" itemprop="url" rel="index">
                    <span itemprop="name">js</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/10/15/js-计算两个时间的时间差/" class="leancloud_visitors" data-flag-title="js 计算两个时间的时间差">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,402 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  5分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="写在前面："><a href="#写在前面：" class="headerlink" title="写在前面："></a>写在前面：</h2><p>如题，就像题目说的需要计算出时间差，虽然不太难，但这个需求经常会在项目中遇到的，我在这边做一下整理，希望能够尽量全的整理出来。有需要的朋友可以做一下参考，喜欢的可以点波赞，或者关注一下，希望可以帮到大家。</p>
<h2 id="计算时间差原理："><a href="#计算时间差原理：" class="headerlink" title="计算时间差原理："></a>计算时间差原理：</h2><h3 id="getTime-方法"><a href="#getTime-方法" class="headerlink" title="getTime()方法"></a>getTime()方法</h3><p>方法定义： getTime() 方法可返回距 1970 年 1 月 1 日之间的毫秒数。</p>
<p>通常我们计算时间差都是通过获取两个时间数据，然后分别使用getTime（）方法返回与固定的1970 年 1 月 1 日的时间差，通过对返回毫秒数的差，换算成时间单位，得出两个时间的时间差。</p>
<h2 id="开始操作："><a href="#开始操作：" class="headerlink" title="开始操作："></a>开始操作：</h2><p>首先你会有一串初始的时间数据，然后通过 new Date(你的时间数据)，将你的数据<strong>转成Date对象</strong>的形式。</p>
<pre><code>var t1=&quot;2017/08/28 04:56:38&quot;; //数据
var dateBegin = new Date(t1);//转化为Date对象的形式
//Mon Aug 28 2017 04:56:38 GMT+0800 (中国标准时间)  这里就是Date对象的数据形式
</code></pre><h3 id="时间格式"><a href="#时间格式" class="headerlink" title="时间格式"></a>时间格式</h3><p>这里的话就要注意一下后端给的<strong>时间数据格式</strong>的问题，比如下面两种：</p>
<pre><code>第一种：&quot;2017/08/28 04:56:38&quot;//这种格式不用再进行处理
第二种：&quot;2017-08-01 18:56:38&quot;//这种格式就要进行处理
</code></pre><p>因为new Date()方法不能处理第二种数据，所以我们这里需要<strong>将第二种数据格式转化为第一种数据的格式</strong>。</p>
<pre><code>var t1=&quot;2017-05-12 00:13:53&quot;;
var dateBegin = new Date(d1.replace(/-/g, &quot;/&quot;));//replace方法将-转为/
</code></pre><p>不知道大家是什么情况，反正因为我们后端给我的数据就是第二种的，所以我会提一下这个东西（捂脸）。</p>
<h4 id="另一个时间数据"><a href="#另一个时间数据" class="headerlink" title="另一个时间数据:"></a>另一个时间数据:</h4><p>既然是时间差的话，就肯定要有两个数据，不然怎么两相比较，一般两个数据中都会有一个当前时间的数据。</p>
<pre><code>var dateEnd = new Date();//当前时间数据
</code></pre><h3 id="完整计算时间差-天、小时、分钟、秒-的代码："><a href="#完整计算时间差-天、小时、分钟、秒-的代码：" class="headerlink" title="完整计算时间差(天、小时、分钟、秒)的代码："></a>完整计算时间差(天、小时、分钟、秒)的代码：</h3><p>先获取之间的毫秒差，通过毫秒差换算出你所需要的时间单位，然后时间单位之间的换算根据的是他们的倍数关系。</p>
<pre><code>function timeFn(d1) {//di作为一个变量传进来
    //如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
    var dateBegin = new Date(d1.replace(/-/g, &quot;/&quot;));//将-转化为/，使用new Date
    var dateEnd = new Date();//获取当前时间
    var dateDiff = dateEnd.getTime() - dateBegin.getTime();//时间差的毫秒数
    var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));//计算出相差天数
    var leave1=dateDiff%(24*3600*1000)    //计算天数后剩余的毫秒数
    var hours=Math.floor(leave1/(3600*1000))//计算出小时数
    //计算相差分钟数
    var leave2=leave1%(3600*1000)    //计算小时数后剩余的毫秒数
    var minutes=Math.floor(leave2/(60*1000))//计算相差分钟数
    //计算相差秒数
    var leave3=leave2%(60*1000)      //计算分钟数后剩余的毫秒数
    var seconds=Math.round(leave3/1000)
    console.log(&quot; 相差 &quot;+dayDiff+&quot;天 &quot;+hours+&quot;小时 &quot;+minutes+&quot; 分钟&quot;+seconds+&quot; 秒&quot;)
    console.log(dateDiff+&quot;时间差的毫秒数&quot;,dayDiff+&quot;计算出相差天数&quot;,leave1+&quot;计算天数后剩余的毫秒数&quot;
        ,hours+&quot;计算出小时数&quot;,minutes+&quot;计算相差分钟数&quot;,seconds+&quot;计算相差秒数&quot;);
}
var t3=&quot;2017-08-18 04:56:38&quot;;
timeFn(t3);
</code></pre><p><img src="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/3ffd4a7df082edd1f1ed6e413cfc35eb?raw=true" alt="demo时间差数据截图"></p>
<h3 id="不成熟的计算月、年"><a href="#不成熟的计算月、年" class="headerlink" title="不成熟的计算月、年:"></a>不成熟的计算月、年:</h3><pre><code>//这里的dayDiff就是上文计算出的天数差
let monthDiff=Math.floor(dayDiff/30);//以30天为一个月不够精准严谨
//获取相差的月份
  if (monthDiff&lt;12){
    timeThis=monthDiff+&quot;个月前发布&quot;;//获取相差的月份
    return
  }
  let yearDiff=Math.floor(monthDiff/12);//获取相差的年份
  if(yearDiff&gt;=1){
    timeThis=yearDiff+&quot;年前发布&quot;;
    return
  }
</code></pre><p>当天数相差较大的时候，单纯计算天数已经不能满足需求了，因为我们PM说的统一以30天为一个月的分界线，然后这里月份的计算情况感觉很复杂的样子没有继续研究下去。</p>
<h3 id="获取当前月份的天数"><a href="#获取当前月份的天数" class="headerlink" title="获取当前月份的天数"></a>获取当前月份的天数</h3><pre><code> function getDays() {
    //构造当前日期对象
    var date = new Date();
    var year = date.getFullYear();//获取年份
    var mouth = date.getMonth() + 1;//获取当前月份
    var days;//定义当月的天数；
    if (mouth == 2) {//当月份为二月时，根据闰年还是非闰年判断天数
        days = year % 4 == 0 ? 29 : 28;
    }
    else if (mouth == 1 || mouth == 3 || mouth == 5 || mouth == 7 || mouth == 8 || mouth == 10 || mouth == 12) {
        //月份为：1,3,5,7,8,10,12 时，为大月.则天数为31；
        days = 31;
    }
    else {
        //其他月份，天数为：30.
        days = 30;
    }
    return days;
}
</code></pre><p>网上找了个获取当前月份天数的函数，上面的注释也足够全，我就一起贴上来，连接在下面。</p>
<h2 id="后话"><a href="#后话" class="headerlink" title="后话"></a>后话</h2><p>上面就是本文计算时间差的内容了，希望看完本文能给大家一点帮助。最后一个提示：一般需要处理的数据不会只有一两个，很可能会给一个数组，你需要处理每个数组元素的时间数据，这时候建议用forEach()函数遍历整个数组。</p>
<p><strong>最后</strong>：如需转载，请放上原文链接并署名。码字不易，<strong>感谢</strong>支持！本人写文章本着交流记录的心态，写的不好之处，不撕逼，但是欢迎指点。然后就是希望看完的朋友点个<strong>喜欢</strong>，也可以<strong>关注</strong>一下我。<br><a href="http://obkoro1.com/" target="_blank" rel="noopener">blog网站</a>  and <strong><a href="https://juejin.im/user/58714f0eb123db4a2eb95372" target="_blank" rel="noopener">掘金个人主页</a> </strong></p>
<p>以上2017.10.15</p>
<h3 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料:"></a>参考资料:</h3><p><a href="http://www.cnblogs.com/rzm2wxm/p/5749151.html" target="_blank" rel="noopener">Js 获取当前月的天数</a><br><a href="http://blog.csdn.net/wei_jie_zhang/article/details/45873837" target="_blank" rel="noopener"> Js计算时间差（天、小时、分钟、秒）</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>听说，打赏我的人最后都找到了真爱。</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/pay/weixin.jpg" alt="OBKoro1 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/pay/ali.jpg" alt="OBKoro1 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/js/" rel="tag"><i class="fa fa-tag"></i> js</a>
          
            <a href="/tags/时间差/" rel="tag"><i class="fa fa-tag"></i> 时间差</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/10/11/vue-cli-npm-run-build空白页的两个坑-webpack-gzip文件压缩优化打包文件/" rel="next" title="vue-cli npm run build空白页的两个坑 webpack gzip文件压缩优化打包文件">
                <i class="fa fa-chevron-left"></i> vue-cli npm run build空白页的两个坑 webpack gzip文件压缩优化打包文件
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/10/23/在vue项目中-如何定义全局变量-全局函数/" rel="prev" title="在vue项目中 如何定义全局变量 全局函数">
                在vue项目中 如何定义全局变量 全局函数 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          
            <img class="site-author-image" itemprop="image"
              src="/uploads/hand1.jpg"
              alt="OBKoro1" />
          
            <p class="site-author-name" itemprop="name">OBKoro1</p>
            <p class="site-description motion-element" itemprop="description">种一棵树最好的时间是十年前,其次是现在</p>
        </div>

        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives">
            
                <span class="site-state-item-count">105</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">20</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">74</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/OBKoro1" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>GitHub</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/58714f0eb123db4a2eb95372" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-globe"></i>掘金</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://obkoro1.com/web_accumulate/" target="_blank" title="前端积累">
                  
                    <i class="fa fa-fw fa-globe"></i>前端积累</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://segmentfault.com/u/obkoro1/articles" target="_blank" title="segmentfault">
                  
                    <i class="fa fa-fw fa-globe"></i>segmentfault</a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#写在前面："><span class="nav-number">1.</span> <span class="nav-text">写在前面：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#计算时间差原理："><span class="nav-number">2.</span> <span class="nav-text">计算时间差原理：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#getTime-方法"><span class="nav-number">2.1.</span> <span class="nav-text">getTime()方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#开始操作："><span class="nav-number">3.</span> <span class="nav-text">开始操作：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#时间格式"><span class="nav-number">3.1.</span> <span class="nav-text">时间格式</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#另一个时间数据"><span class="nav-number">3.1.1.</span> <span class="nav-text">另一个时间数据:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#完整计算时间差-天、小时、分钟、秒-的代码："><span class="nav-number">3.2.</span> <span class="nav-text">完整计算时间差(天、小时、分钟、秒)的代码：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#不成熟的计算月、年"><span class="nav-number">3.3.</span> <span class="nav-text">不成熟的计算月、年:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#获取当前月份的天数"><span class="nav-number">3.4.</span> <span class="nav-text">获取当前月份的天数</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#后话"><span class="nav-number">4.</span> <span class="nav-text">后话</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#参考资料"><span class="nav-number">4.1.</span> <span class="nav-text">参考资料:</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2017 &mdash; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">OBKoro1</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">
      156.0k
    </span>
  
</div>




<div>
<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span class="site-uv"><i class="fa fa-user"></i> 访问用户： <span class="busuanzi-value" id="busuanzi_value_site_uv">21621</span> 人 </span>
<span class="site-pv"><i class="fa fa-eye"></i> 访问次数： <span class="busuanzi-value" id="busuanzi_value_site_pv">68503</span> 次</span>

</div>



        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>


  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  








  



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("9ANFp60h6oVyxIPGlau3NOA4-gzGzoHsz", "tMdNuKMbFtN4QsekeNVu83TV");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>

